import moment from "moment";
import { ref, computed } from "vue";
import { getVppListAll, operationBaseLine, getBaseLine } from "@/api/vppUser";
import { ElMessage } from "element-plus";
import { timeSlot } from "@/utils";
export function useCalendarHook() {
  // 获取 当前 年 月
  let nowYear = parseInt(moment().format("YYYY"));
  let nowMonth = parseInt(moment().format("MM"));
  let nowDay = moment().format("YYYY-MM-DD");
  let disabledYear = 2020;
  let disabledMonth = 12;

  const selYear = ref(nowYear);
  const selMonth = ref(nowMonth);
  const selValue = ref([]);
  const calenderTitle = ref(`${nowYear} 年 ${nowMonth} 月`);

  const pervYearClick = computed(() => {
    // 上一年 是否可以点
    let time1 = moment(`${selYear.value - 1}-${selMonth.value}`);
    let time2 = moment(`${disabledYear}-${disabledMonth}`);
    if (time1.isAfter(time2)) {
      return true;
    } else {
      return false;
    }
  });
  const pervMonthClick = computed(() => {
    // 上一月 是否可以点
    let time1 = moment(`${selYear.value}-${selMonth.value}`).subtract(
      "1",
      "month"
    );
    let time2 = moment(`${disabledYear}-${disabledMonth}`);
    if (time1.isAfter(time2)) {
      return true;
    } else {
      return false;
    }
  });
  const nextYearClick = computed(() => {
    // 上一年 是否可以点
    // let time1 = moment(`${selYear.value + 1}-${selMonth.value}`);
    // let nowTime = moment();
    return true;
    // if (time1.isBefore(nowTime)) {
    //   return true;
    // } else {
    //   return false;
    // }
  });
  const nextMonthClick = computed(() => {
    // 上一年 是否可以点
    // let time1 = moment(`${selYear.value}-${selMonth.value}`).add("1", "month");
    // let nowTime = moment();
    return true;
    // if (time1.isBefore(nowTime)) {
    //   return true;
    // } else {
    //   return false;
    // }
  });

  const calendar = ref(null);
  const selectDate = async (val: string) => {
    let lYear = selYear.value;
    let lMonth = selMonth.value;
    if (val === "prev-year") {
      lYear = lYear - 1;
    }
    if (val === "prev-month") {
      if (lMonth === 1) {
        lMonth = 12;
        lYear = lYear - 1;
      } else {
        lMonth = lMonth - 1;
      }
    }
    if (val === "next-year") {
      lYear = lYear + 1;
    }
    if (val === "next-month") {
      if (lMonth === 12) {
        lMonth = 1;
        lYear = lYear + 1;
      } else {
        lMonth = lMonth + 1;
      }
    }
    if (lYear < disabledYear) {
      return;
    }
    if (lYear === disabledYear && lMonth < disabledMonth) {
      return;
    }
    // if (lYear > nowYear) {
    //   return;
    // }
    // if (lYear === nowYear && lMonth > nowMonth) {
    //   return;
    // }
    selYear.value = lYear;
    selMonth.value = lMonth;
    calenderTitle.value = `${selYear.value} 年 ${selMonth.value} 月`;
    // await getMonthDataShowCalener(selYear.value, selMonth.value);
    calendar.value.selectDate(val);
  };
  const dayIsHaveMonth = (day, month) => {
    let dateToCheck = day;
    let monthToCheck = month;
    let momentDate = moment(dateToCheck);
    let startOfMonth = moment(monthToCheck, "YYYY-MM").startOf("month");
    let endOfMonth = moment(monthToCheck, "YYYY-MM").endOf("month");
    let isInMonth =
      (momentDate.isAfter(startOfMonth) && momentDate.isBefore(endOfMonth)) ||
      momentDate.isSame(startOfMonth) ||
      momentDate.isSame(endOfMonth);
    return isInMonth;
  };
  const setActiveDay = data => {
    let isHave = dayIsHaveMonth(data.day, `${selYear.value}-${selMonth.value}`);
    if (isHave) {
      let index = selValue.value.findIndex(i => i === data.day);
      if (index > -1) {
        selValue.value.splice(index, 1);
      } else {
        if (selValue.value.length < 5) {
          selValue.value.push(data.day);
        } else {
          ElMessage({
            message: "最多只能选择五个自然日(可以点击已选择的关闭)!",
            type: "warning"
          });
        }
      }
    }
  };
  const vppList = ref([]);
  const activeVppId = ref(null);
  // const calendarData = ref([]);
  const vppUserList = ref([]);
  const activeVppAndUser = ref([]);
  getVppListAll().then(async res => {
    vppList.value = res || [];
    if (vppList.value.length) {
      activeVppId.value = vppList.value[0].id;
      vppUserList.value = vppList.value[0].vppUserResponse;
      vppUserList.value.forEach((item, index) => {
        if (index === 0) {
          item.active = true;
        } else {
          item.active = false;
        }
      });
      let active = vppUserList.value.find(item => item.active);
      let data = await getBaseLine({ vppUserId: active.id, dataType: 2 });
      options.value.title.text = `${active.name} ${data.dataDate.split(" ")[0]} 基线数据`;
      options.value.series[0].data = keys.map(key => data[key] || null);
    }
  });
  const setActive = row => {
    vppUserList.value.forEach(item => {
      if (item.id === row.id) {
        item.active = true;
      } else {
        item.active = false;
      }
    });
  };
  const showDateItemCell = data => {
    let m = moment(data.day);
    return dayIsHaveMonth(data.day, `${selYear.value}-${selMonth.value}`)
      ? m.format("MM-DD")
      : "";
  };
  // function getRandomNumberInRange(start, end) {
  //   const random = Math.random() * (end - start + 1) + start;
  //   return parseFloat(random.toFixed(2));
  // }

  let data = [];
  const times = timeSlot(15);
  const keys = Array(96)
    .fill(1)
    .map((_, index) => index + 1)
    .map(i => `p${i > 9 ? i : "0" + i}`);
  const options = ref({
    color: [
      "#fac858",
      "#91cc75",
      "#ee6666",
      "#3ba272",
      "#fc8452",
      "#9a60b4",
      "#ea7ccc"
    ],
    title: {
      show: true,
      text: "根据选中的五个自然日和用户计算出的基线",
      left: "center"
    },
    grid: {
      bottom: "15%"
    },
    legend: {
      show: true,
      top: "10%",
      data: ["基线"]
    },
    dataZoom: [
      {
        type: "inside",
        start: 0,
        end: 100
      },
      {
        show: true,
        type: "slider",
        top: "90%",
        start: 0,
        end: 100
      }
    ],
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      splitLine: {
        show: false
      },
      data: times
    },
    yAxis: [
      {
        // name: "功率曲线",
        // nameLocation: "end",
        splitLine: {
          show: false
        },
        axisLine: {
          show: true
        }
      }
    ],
    series: [
      // {
      //   name: "响应能力",
      //   type: "candlestick",
      //   // 最大值  最大值 - 1 最小值 最小值+1
      //   data: data.map(item => {
      //     return [item[1], item[1] - 0.01, item[3], item[3] + 0.01];
      //   })
      // },
      // {
      //   name: "响应能力下限",
      //   type: "candlestick",
      //   // 最小值+1  最小值 - 1 最小值 - 1  最小值+1
      //   data: data.map(item => {
      //     return [
      //       item[3] + 0.01,
      //       item[3] - 0.01,
      //       item[3] - 0.01,
      //       item[3] + 0.01
      //     ];
      //   })
      // },
      {
        name: "基线",
        smooth: true,
        type: "line",
        data: data
      }
    ]
  });
  const loading = ref(false);
  const reset = () => {
    selValue.value = [];
    vppUserList.value.forEach(item => {
      item.active = false;
    });
    options.value.title.text = `根据选中的五个自然日和用户计算出的基线`;
    options.value.series[0].data = [];
  };
  const comSubit = async () => {
    let active = vppUserList.value.find(item => item.active);
    if (selValue.value.length !== 5) {
      ElMessage({
        message: "请点击日历选择共5个自然日!",
        type: "warning"
      });
      return;
    }
    if (!active) {
      ElMessage({
        message: "请选择一个用户!",
        type: "warning"
      });
      return;
    }
    loading.value = true;
    await operationBaseLine({
      days: selValue.value,
      vppUserId: active.id,
      dataType: 2
    });
    let data = await getBaseLine({ vppUserId: active.id, dataType: 2 });
    options.value.title.text = `${active.name} ${data.dataDate.split(" ")[0]} 基线数据`;
    options.value.series[0].data = keys.map(key => data[key] || null);
    loading.value = false;
    // options.value.series[0].data = new Array(96)
    //   .fill(1)
    //   .map(() => getRandomNumberInRange(10, 20));
  };
  const vppChange = async e => {
    loading.value = true;
    let p = vppList.value.find(i => i.id === e);
    vppUserList.value = p.vppUserResponse;
    vppUserList.value.forEach(item => {
      item.active = false;
    });
    vppUserList.value.forEach((item, index) => {
      if (index === 0) {
        item.active = true;
      } else {
        item.active = false;
      }
    });
    let active = vppUserList.value.find(item => item.active);
    let data = await getBaseLine({ vppUserId: active.id, dataType: 2 });
    options.value.title.text = `${active.name} ${data.dataDate.split(" ")[0]} 基线数据`;
    options.value.series[0].data = keys.map(key => data[key] || null);
    loading.value = false;
  };
  const rowClick = async row => {
    let bactive = vppUserList.value.find(item => item.active);
    if (bactive && row.id === bactive.id) return;
    vppUserList.value.forEach(item => {
      if (item.id === row.id) {
        item.active = true;
      } else {
        item.active = false;
      }
    });
    let active = vppUserList.value.find(item => item.active);
    loading.value = true;
    let data = await getBaseLine({ vppUserId: active.id, dataType: 2 });
    options.value.title.text = `${active.name} ${data.dataDate.split(" ")[0]} 基线数据`;
    options.value.series[0].data = keys.map(key => data[key] || null);
    loading.value = false;
  };
  return {
    loading,
    nowYear,
    nowMonth,
    nowDay,
    disabledYear,
    disabledMonth,
    selYear,
    selMonth,
    selValue,
    calenderTitle,
    pervYearClick,
    pervMonthClick,
    nextYearClick,
    nextMonthClick,
    calendar,
    selectDate,
    dayIsHaveMonth,
    setActiveDay,
    vppList,
    activeVppId,
    vppUserList,
    activeVppAndUser,
    showDateItemCell,
    setActive,
    comSubit,
    options,
    vppChange,
    rowClick,
    reset
  };
}
